﻿using System;
using System.Xml.Linq;
using System.Collections.Generic;

using Engine;

using Game;

namespace ApiToolkit
{
	public class Vector3PropertyEditor : CanvasWidget
	{
		PropertyEditor_Common Editor;

		SliderWidget Value1Slider;
		TextBoxWidget Value1TextBox;

		SliderWidget Value2Slider;
		TextBoxWidget Value2TextBox;

		SliderWidget Value3Slider;
		TextBoxWidget Value3TextBox;

		ButtonWidget ApplyButton;

		Vector3 value;
		public Vector3PropertyEditor(int content, string targetProperty, ContainerWidget parent)
		{
			try
			{
				this.Editor = new PropertyEditor_Common(content, targetProperty);
				XElement xelement = ContentManager.Get<XElement>("Widgets/Vector3PropertyEditor");
				LoadContents(this, xelement);
				
				value = (Vector3)Editor.TargetPropertyValue;
				
				Value1Slider = Children.Find<SliderWidget>("Value1Slider");
				Value1TextBox = Children.Find<TextBoxWidget>("Value1TextBox");
				Value1TextBox.Text = value.X.ToString();

				Value2Slider = Children.Find<SliderWidget>("Value2Slider");
				Value2TextBox = Children.Find<TextBoxWidget>("Value2TextBox");
				Value2TextBox.Text = value.Y.ToString();
				
				Value3Slider = Children.Find<SliderWidget>("Value3Slider");
				Value3TextBox = Children.Find<TextBoxWidget>("Value3TextBox");
				Value3TextBox.Text = value.Z.ToString();
				
				ApplyButton = Children.Find<ButtonWidget>("ApplyButton");
			}
			catch (Exception ex)
			{
				Log.Error(ex.ToString());
				throw;
			}
		}

		public override void Update()
		{
			UpdateValue(Value1Slider, Value1TextBox, ref value.X);
			UpdateValue(Value2Slider, Value2TextBox, ref value.Y);
			UpdateValue(Value3Slider, Value3TextBox, ref value.Z);
			
			if(ApplyButton.IsClicked)
			{
				Editor.TargetPropertyValue = value;
			}
		}
		private void UpdateValue(SliderWidget slider, TextBoxWidget TextBox, ref float value)
		{
			if(slider.IsSliding)
			{
				TextBox.Text = (value + slider.Value).ToString();
			}
			else if(slider.SlidingCompleted)
			{
				value = value + slider.Value;
				slider.Value = 0;
				TextBox.Text = value.ToString();
			}
			else if(TextBox.Text != value.ToString())
			{
				try
				{
					value = float.Parse(TextBox.Text);
				}
				catch
				{
					TextBox.Text = value.ToString();
				}
			}
		}
	}
}